#!/usr/bin/env perl

use strict;
use warnings;
use File::Slurp;

# number of tests
my $n = 6;

# template file
my $template_file = "template-3.tex";

# mapping file
my $map_file = "test-3.map";

# additional counter
my $counter = 0;

# initialize template
my $template = read_file($template_file);

# initialize mappings
my $mapping_text = read_file($map_file);
my $pattern = "ex"; # ex1, ex2, ... 
my %mapping = ();
my %problems = ();
local $_ = $mapping_text;
while (m/\*(.*?)\*\->\*(.*?)\*/sg) {
    # initialize mapping of ex1 to file.problems
    $mapping{$1} = $2;

    # initialize mapping from "file.problems" to list of problems
    my $text = read_file($2);

    # read problems into array
    my @pbs = ();
    while ($text =~ m/%%%(.*?)%%%/sg) {
	push(@pbs, $1);
    }

    # save mapping
    $problems{$2} = \@pbs;
}

# while ( my ($key, $value) = each(%problems) ) {
#        print "$key => @$value\n";
#    }

# exit(0);
for (my $i = 0; $i < $n; $i ++) {
    
    # prepare new template
    local $_ = $template;
    my $basename = "Test$i";
    my $testname = "$basename.tex";
    unlink($testname);

    # set subject no
    s/subject/($i+1)/sge;
    
    # add exercises    
    while ( my ($key, $value) = each(%mapping) ) {
#        print "$key => "; print choose($value); print "\n";
        s/$key/choose($value)/sge;
    }
    $counter++;

    # save test
    write_file($testname, $_);

    # generate pdfs
    $_ = `pdflatex $testname`;
    print;

    # cleanup
    unlink("$basename.aux");
    unlink("$basename.log");

}

sub choose {
    my $file = shift;
    my $size = scalar(@{$problems{$file}});
    my $exercise = $problems{$file}[$counter % $size];
#    print "Counter $counter\nSize: $size\nChosen: $exercise\n\n";
    $exercise;
}

exit(0);

while ( my ($key, $value) = each(%mapping) ) {
        print "$key => $value\n";
    }

